<template>
  <div class="content">
    <div>
      <teacher-menu></teacher-menu>
    </div>
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">
      <header class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-semibold text-gray-800">教师工作台</h1>
        <div class="flex items-center">
          <i class="fas fa-cloud-sun text-2xl text-blue-400"></i>
          <p class="text-sm text-gray-500" style="margin-right: 10px;">{{ weather.city }}</p>
          <p class="text-xl font-bold" style="margin-right: 20px;">{{ weather.temp }}°C</p>

          <!-- 通知按钮和弹窗 -->
          <el-popover
              v-model="popoverVisible"
              placement="bottom-end"
              popper-class="notification-popover"
              style="margin-right: 20px;"
              trigger="click"
              width="400"
          >
            <div class="notification-container">
              <div class="message-list">
                <div
                    v-for="(message, index) in currentPageMessages"
                    :key="index"
                    class="message-card hover:shadow-md"
                    @click="markAsRead(message)"
                >
                  <el-avatar :size="40" :src="message.YHZP" class="mr-3"/>
                  <div class="message-content">
                    <div class="message-header">
                      <span class="sender">{{ message.CFZXM }}</span>
                      <span class="time">{{ formatDate(message.CFSJ) }}</span>
                    </div>
                    <p>{{ message.DZNR }}</p>
                  </div>
                  <div v-if="!message.YDBZ" class="unread-dot"></div>
                </div>
              </div>
              <el-pagination
                  :current-page.sync="currentPage"
                  :page-size="pageSize"
                  :total="messages.length"
                  class="pagination"
                  layout="prev, pager, next"
                  @current-change="handlePageChange"
              />
            </div>

            <button slot="reference" class="hover:text-slate-600 relative">
              <i class="el-icon-bell text-xl"></i>
              <span
                  v-show="messages.some(msg => msg.YDBZ === 0)"
                  class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"
              ></span>
            </button>
          </el-popover>
          <el-dropdown>
            <span class="el-dropdown-link">
              {{ UserInfo.name }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>个人中心</el-dropdown-item>
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </header>

      <!-- 数据概览 -->
      <el-row :gutter="20" class="mb-6">
        <el-col v-for="(item, index) in statistics" :key="index" :lg="6" :md="6" :sm="12" :xs="24"
                @click="handleStatistics(item)">
          <el-card shadow="hover">
            <div class="flex items-center" @click="handleStatistics(item)">
              <div :class="`icon-container bg-${item.color}-100 p-3 rounded-full mr-4`">
                <i :class="`el-icon-${item.icon} text-${item.color}-500 text-xl`"></i>
              </div>
              <div>
                <div class="text-gray-500 text-sm">{{ item.title }}</div>
                <div class="text-2xl font-bold">{{ item.value }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 主要区域 -->
      <el-row :gutter="20">
        <!-- 就业数据图表 -->
        <el-col :span="16">
          <el-card class="mb-6" shadow="never">
            <div slot="header" class="clearfix">
              <span class="font-semibold">就业数据统计</span>
            </div>
            <div ref="employmentChart" style="height: 300px;"></div>
          </el-card>
        </el-col>

        <!-- 待办事项 -->
        <el-col :span="8">
          <el-card shadow="never" style="height: 404px;">
            <div slot="header" class="clearfix">
              <span class="font-semibold">待办事项</span>
              <el-button style="float: right; padding: 3px 0" type="text">更多</el-button>
            </div>

            <el-table :data="todoList" style="width: 100%">
              <el-table-column label="内容" prop="Msg"></el-table-column>
              <el-table-column label="类型" prop="LX" width="80">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.LX | statusType" size="mini">{{ scope.row.LX }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button size="small" type="text" @click="handleTodo(scope.row)">处理</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <el-card class="mt-6" shadow="never">
        <div slot="header" class="clearfix">
          <span class="font-semibold">最新就业信息</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="gotoXstd">查看更多</el-button>
        </div>
        <el-table :data="recentJobs" style="width: 100%">
          <el-table-column label="企业名称" prop="GSMC"></el-table-column>
          <el-table-column label="职位" prop="GWMC"></el-table-column>
          <el-table-column label="学生姓名" prop="XSXM"></el-table-column>
          <el-table-column label="投递时间" prop="TDSJ"></el-table-column>

          <el-table-column label="状态" width="120" fixed="left">
            <template #default="{row}">
              <el-tag v-show="row.HYDM===0" :type="row.QRDM === 1 ? 'success' : 'warning'">
                {{ row.QRDM === 1 ? '已确认' : '待确认' }}
              </el-tag>
              <el-tag v-show="row.HYDM===1" type="success">
                单位已回应
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </main>
  </div>
</template>

<script>
import TeacherMenu from "@/components/teacher/Teacher_menu.vue";
import * as echarts from 'echarts';
import axios from "axios";

export default {
  name: 'TeacherDashboard',
  components: {TeacherMenu},
  data() {
    return {
      popoverVisible: false,
      currentPage: 1,
      pageSize: 5,
      UserInfo: {
        id: '',
        name: '',
        role: '',
        username: '',
      },
      weather: {
        city: "上海",
        temp: 25,
      },
      teacherName: '张老师',
      messageCount: 3,

      statistics: [
        {title: '入驻单位', icon: 'office-building', value: 25, color: 'blue', url: '/teacher/rzdw'},
        {title: '岗位数', icon: 'postcard', value: 8, color: 'orange', url: "/teacher/job"},
        {title: '招聘公告', icon: 'message', value: 3, color: 'green', url: "/teacher/TeacherZpggView"},
        {title: '负责学生数', icon: 'user', value: 86, color: 'purple', url: "/teacher/mystudents"},
      ],
      todoList: [],
      recentJobs: [],
      chartInstance: null,
      messages: [],// 未读消息
    }
  },
  computed: {
    currentPageMessages() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.messages.slice(start, start + this.pageSize);
    },
  },
  watch: {
    popoverVisible(val) {
      if (!val) {
        // 弹窗被关闭
        console.log('Popover 已关闭')
        this.handlePopoverClosed()
      }
    }
  },
  filters: {
    statusType(status) {
      const typeMap = {
        '已确认': 'success',
        '待审核': 'warning',
        '紧急': 'danger',
        '普通': 'info'
      }
      return typeMap[status] || 'info'
    }
  },
  mounted() {
    this.getLoginUserInfo();

  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
  },
  methods: {
    // 防抖
    gotoXstd: _.debounce(function(){
      this.$router.push({
        path: '/teacher/xstd',
      });
    }, 500),
    // 获取最近投递的三个
    getResentTddata() {
      axios.get("/tdjlk/getTdjlk", {
        params: {
          Style:5, YHM: this.UserInfo.username, GWDM:-1
        }
      }).then(response => {
        if (response.data.result) {
          this.recentJobs = response.data.data.slice(0, 3);
        } else {
          this.$message.error(response.data.msg);
        }
      }).catch(error => {
        this.$message.error('获取投递数据失败:' + error.message);
      });
    },
  handlePopoverClosed() {
    axios.get("/xxdmk/setRead", {
      params: {
        YHM: this.UserInfo.username,
        YHSFDM: 2
      }
    }).then(response => {
      if (!response.data.result) {
        $.confirm({
          title: '⚠️ 系统崩溃警告',
          content: `<div style="color:#b00020;font-weight:bold;font-size:16px;">
                更新消息状态失败（灾难性故障）：
                <br><br>
                <code>${response.data.data}</code>
              </div>`,
          type: 'red',
          typeAnimated: true,
          boxWidth: '500px',
          useBootstrap: false, // 更自由的样式控制
          backgroundDismiss: false, // 禁止点击背景关闭
          theme: 'supervan', // 更显眼的主题风格
          buttons: {
            '⚠ 重新尝试': {
              btnClass: 'btn-red',
              action: () => {
                this.handlePopoverClosed(); // 重新执行
              }
            }
          }
        });
      } else {
        // 设置为已读
        for (let i = 0; i < this.messages.length; i++) {
          this.messages[i].YDBZ = 1;
        }
      }
    }).catch(error => {
      console.log(error);
      $.confirm({
        title: '⚠️ 网络崩溃警告',
        content: `<div style="color:#b00020;font-weight:bold;font-size:16px;">
                更新消息状态失败（一般性故障）：
                <br><br>
                <code>${error.message}</code>
              </div>`,
        type: 'red',
        typeAnimated: true,
        boxWidth: '500px',
        useBootstrap: false, // 更自由的样式控制
        backgroundDismiss: false, // 禁止点击背景关闭
        theme: 'supervan', // 更显眼的主题风格
        buttons: {
          '⚠ 重新尝试': {
            btnClass: 'btn-red',
            action: () => {
              this.handlePopoverClosed(); // 重新执行
            }
          }
        }
      });
    });
  },
  markAsRead(message) {
    // 标记已读逻辑
    message.YDBZ = 1;
  },
  async showTjtData() {
    await this.$nextTick();

    let data = [];
    try {
      const response = await axios.get(
          `/data/getTdtjData?YHM=${this.UserInfo.username}&YHSFDM=2&JsSeven=1`
      );
      const resData = response.data;
      if (resData.result && Array.isArray(resData.data)) {
        data = resData.data;
      } else {
        console.warn('返回数据不是数组：', resData.data);
      }
    } catch (err) {
      console.error('获取统计数据出错：', err);
      return;
    }

    const xData = data.map(item => item.day);
    const yData = data.map(item => item.count);

    const chartDom = this.$refs.employmentChart;
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
    this.chartInstance = echarts.init(chartDom);

    const option = {
      tooltip: {trigger: 'axis'},
      xAxis: {type: 'category', data: xData},
      yAxis: {type: 'value'},
      series: [{
        data: yData,
        type: 'line',
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: 'rgba(64, 158, 255, 0.6)'},
            {offset: 1, color: 'rgba(64, 158, 255, 0.01)'}
          ])
        }
      }]
    };

    this.chartInstance.setOption(option);
  },
  getWaitoDOthing() {
    axios.get("/data/getWaitTodoData?YHM=" + this.UserInfo.username).then(response => {
      if (response.data.result) {
        this.todoList = response.data.data;
        this.todoList = [];
        this.$nextTick(() => {
          this.todoList = response.data.data;
        });

      } else {
        this.$message.error(response.data.msg);
      }
    }).catch(error => {
      this.$message.error('获取待办事项失败:' + error.message);
    });
  }
  ,
  handleStatistics(item) {
    console.log(item);
  }
  ,
  handlePageChange(page) {
    this.currentPage = page;
  }
  ,
  async getLoginUserInfo() {
    try {
      this.loading = true;
      const response = await axios.get('/user/checkSession');
      if (!response.data.result) {
        this.handleAuthFailure(response.data.msg);
      } else {
        this.UserInfo = {
          name: response.data.name,
          role: response.data.role,
          username: response.data.username
        };
        this.getWaitoDOthing();
        await this.showTjtData();
        this.getIndexCount();
        this.getXxdm();
        this.getResentTddata();// 获取投递数据
      }
    } catch (error) {
      console.error('获取用户信息失败，网络错误！', error);
      this.handleAuthFailure();
    }
  }
  ,
  formatDate(dateStr) {
    return dateStr
        ? new Date(dateStr).toLocaleString(undefined, {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
        : '-';
  }
  ,
  getXxdm() {
    axios.get(`/xxdmk/getXxdmk?YHM=${this.UserInfo.username}&YHSFDM=2`)
        .then((res) => {
          if (res.data.result) {
            this.messages = res.data.data.filter(
                (m) => m.CFZ !== this.UserInfo.username
            );
          }
        })
        .catch(() => {
        });
  }
  ,
  getIndexCount() {
    axios.get("/data/getUserIndexCount", {params: {YHM: this.UserInfo.username, YHSFDM: 2}}).then(response => {
      if (response.data.result) {
        console.log(response.data.data);

        this.statistics[0].value = response.data.data.RZDWS;
        this.statistics[1].value = response.data.data.YXGWS;
        this.statistics[2].value = response.data.data.YSZPGGS;
        this.statistics[3].value = response.data.data.FZXSS;

      } else {
        this.$message.error(response.data.msg);
      }
    }).catch(error => {
      this.$message.error('加载数据失败:' + error.message);
    });
  }
  ,
  initChart() {
    this.chartInstance = echarts.init(document.getElementById('employmentChart'))
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        data: [15, 23, 45, 56, 78, 95],
        type: 'line',
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: 'rgba(64, 158, 255, 0.6)'},
            {offset: 1, color: 'rgba(64, 158, 255, 0.01)'}
          ])
        }
      }]
    }
    this.chartInstance.setOption(option)
  }
  ,
  handleTodo(item) {
    this.$confirm(`确定处理该事项：${item.content}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      this.todoList = this.todoList.filter(t => t.id !== item.id)
      this.$message.success('处理成功')
    })
  }
}
}
</script>

<style scoped>
.icon-container {
  transition: all 0.3s;
}

.el-card:hover .icon-container {
  transform: scale(1.1);
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.icon-box {
  @apply w-12 h-12 rounded-lg flex items-center justify-center;
}

.px-4 {
  padding-left: 0px !important;
}

.stat-card {
  @apply transition-all duration-300 hover:transform hover:scale-105;
}

.chart-card {
  @apply border-0 bg-white rounded-lg shadow-sm;
}

.card-title {
  @apply text-lg font-semibold text-gray-800;
}

.notice-item {
  @apply p-3 bg-gray-50 rounded-lg hover:bg-blue-50 transition-colors;
}

:deep(.el-card__header) {
  @apply border-b-0;
}

/* 消息通知样式 */
.notification-popover {
  padding: 0 !important;
}

.notification-container {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message-card {
  position: relative;
  display: flex;
  align-items: center;
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.message-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.message-content {
  flex: 1;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 0.9em;
  color: #909399;
}

.sender {
  font-weight: bold;
  color: #303133;
}

.time {
  color: #909399;
}

.message-content p {
  margin: 0;
  font-size: 1em;
  color: #606266;
}

.unread-dot {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 8px;
  height: 8px;
  background-color: red;
  border-radius: 50%;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.el-pager li {
  border-radius: 4px;
  transition: background-color 0.2s;
}

.el-pager li:hover {
  background-color: #ecf5ff;
}

.el-pager li.active {
  background-color: #409eff;
  color: #fff;
}
</style>